#include "Configuration.hpp"
#include "UserManager.hpp"
#include "TcpConnection.hpp"
#include <iostream>
using std::unique_lock;
namespace wd{

using TcpConnectionptr = shared_ptr<TcpConnection>;

UserManger * UserManger::_pinstance = nullptr;
UserManger::AutoRelease UserManger::_ar;

UserManger* UserManger::getInstance(){
    if(_pinstance == nullptr){
            _pinstance = new UserManger();
    }
    return _pinstance;
}

void UserManger::add_user_info(TcpConnectionptr tcpconn, shared_ptr<User> user){
    std::unique_lock<mutex> ul(_mutex);
    /* std::cout << "UserManager: add a new userInfo \n"; */
    _users_info[tcpconn] = user;
}

#if 0
void UserManger::del_user_info(TcpConnectionptr tcpconn){
    unique_lock<mutex> ul(_mutex);
    int ret = _users_info.find(tcpconn);
    if(ret != _users_info.end()){
        _users_info.erase(tcpconn);
    }
}
#endif

shared_ptr<User> UserManger::get_single_user(TcpConnectionptr tcpconn){
    auto ret = _users_info.find(tcpconn);
    if(ret != _users_info.end()){
        return ret->second;
    }
    return nullptr;
}

UserManger::UserManger(){
    camera_init();  
}


void UserManger::camera_init(){
    Configuration* config = Configuration::getInstance("./server.conf");
    auto config_map = config->getConfigMap();
    
    int camera_id = stoi(config_map["camera_id"]);
    string rtmp = config_map["rtmp"];
    string rtsp = config_map["rtsp"];
    shared_ptr<Camera> pcam(new Camera);

   pcam->set_rtmp(rtmp);
   pcam->set_rtsp(rtsp);

   _cameras[camera_id] = pcam;

}

string UserManger::get_rtmp(int camera_id){
    auto ret = _cameras.find(camera_id);
    if(ret != _cameras.end()){
        shared_ptr<Camera> pcam = ret->second;
        return pcam->get_rtmp();
    }
    return string("");
}

string UserManger::get_rtsp(int camera_id){
    auto ret = _cameras.find(camera_id);
    if(ret != _cameras.end()){
        shared_ptr<Camera> pcam = ret->second;
        return pcam->get_rtsp();
    }
    return string("");
    
}

map<TcpConnectionptr,shared_ptr<User>>& UserManger::get_all_usersinfo(){
    return _users_info;
}

}



